$(document).ready(function(){
	var numberOfAccountsPerPage = 10;
	var page = 0;
	var module = 'account';
	var timeOutTime = 5000;
	
	var selectPriv = 0;
	var insertPriv = 0;
	var updatePriv = 0;
	var deletePRiv = 0;
	
	var statusSorting = 'ASC';
	var accountCount = 0;
	

	initControl();
	
	// this is synchronous function, so it must runs after initControl
	getPrivs();
	
	shouldListAccount();
	
	function initControl()
	{		
		initEditAccountDialog();
		initRemoveAccountDialog();
		initSortingGlyph();
	}
	
	function drawPaginationHelper(accountCount)
	{
		// $('#accountPagination').pagination({
			// items_per_page: numberOfAccountsPerPage,
			// num_display_entries: 5,
			// current_page: 1,
			// num_edge_entries: ,
			// link_to:"#",
			// prev_text:"Prev",
			// next_text:"Next",
			// ellipse_text:"...",
			// prev_show_always:true,
			// next_show_always:true,
			// renderer:"defaultRenderer",
			// callback:function(){return false;}
		// },opts||{});
	}
	
	function drawPagination()
	{		 
		$.ajax({
			type: 'GET',
			url: '/account/get-account-count',
			success: function(json) {
				var obj = $.parseJSON(json);
				var code = obj.code, accountCount = obj.data;
				if(code == 0) {					
					drawPaginationHelper(accountCount);
				}
			}
		});	// end $.ajax call		
	}
	

	
	function initSortingGlyph()
	{
		$('#ascSorting').click(function(){
			statusSorting = 'DESC';
			loadAccount();
			$(this).hide();
			$('#descSorting').show();			
		});
		
		$('#descSorting').click(function(){
			statusSorting = 'ASC';
			loadAccount();
			$(this).hide();
			$('#ascSorting').show();
		});
	}
	
	function shouldListAccount()
	{
		if(selectPriv) {
			$('#listAccountTableWrapper').show();			
			loadAccount();
			drawPagination();
		} else {
			$('#selectPrivReport').show();
		}
	}
	
	function getPrivs()
	{
		$.ajax({
			url: '/privilege/get-privs',
			data: {module: module},			
			async: false,
			timeout: timeOutTime,
			success: function(json){
				var returnData = $.parseJSON(json);
				var data = returnData.data;
				if(returnData.code == 0) {
					selectPriv = data.SELECT_PRIV;
					insertPriv = data.INSERT_PRIV;
					updatePriv = data.UPDATE_PRIV;
					deletePriv = data.DELETE_PRIV;
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {					
					getPrivs();					
				}
			}
		});
	}
	
	function loadAccount()
	{
		$.get("/account/list", 
			  {from: page * numberOfAccountsPerPage, numberOfAccounts: numberOfAccountsPerPage, statusSorting: statusSorting},
			  function(data){
				  	var returnData = $.parseJSON(data);

					// remove old children
					$('#listAccountTable tbody').empty();
					var accountTableHTML = '';

					for (var i = 0; i < returnData.data.length; i++)
					{
						accountTableHTML += '<tr>';
						accountTableHTML += '<td class="accountNumber">' + (i + 1) + '</td>';

						accountTableHTML += '<td>' + returnData.data[i].FULLNAME + '</td>';						
						accountTableHTML += '<td>' + returnData.data[i].ADDRESS + '</td>';
						accountTableHTML += '<td>' + returnData.data[i].PHONE + '</td>';						
						accountTableHTML += '<td>' + returnData.data[i].MOBILE + '</td>';
						accountTableHTML += '<td>' + (returnData.data[i].STATUS == 0 ? 'Đang xử lý' : 'Hoàn tất') + '</td>';
						accountTableHTML += '<td><a href="http://bmsc.com.vn/documents/' + returnData.data[i].INFORMATION_FILE + '">' + 'Tải về' + '</a></td>';
						accountTableHTML += '<td><a href="http://bmsc.com.vn/documents/' + returnData.data[i].CONTRACT_FILE + '">' + 'Tải về' + '</a></td>';
						accountTableHTML += '<td><a href="http://bmsc.com.vn/documents/' + returnData.data[i].AUTHORIZE_FILE + '">' + 'Tải về' + '</a></td>';
							
						if(updatePriv == 0 && deletePriv == 0) {
							accountTableHTML += '<td align="center">Không có</td>';
						} else {
							accountTableHTML += 
							'<td align="center">' + 
							(updatePriv ? '<a id="e' + returnData.data[i].ID + '" href="#" class="editAccount">Sửa</a>' : '') + 
							(updatePriv && deletePriv ? ' | ' : '') +
							(deletePriv ? '<a id="r' + returnData.data[i].ID + '" href="#" class="removeAccount">Xóa</a>' : '') + 
							'</td>';
						}				
						accountTableHTML += '</tr>';
					}
					$('#listAccountTable tbody').append(accountTableHTML);					
					// Edit account event handler
					$(".editAccount").click(function(){
						var accountID = $(this).attr("id").substring(1);
						editAccount(accountID);
						return false;
					});
					// Remove account event handler
					$(".removeAccount").click(function(){
						var accountID = $(this).attr("id").substring(1);
						var accountNumber = $(this).parent('td').parent('tr').find('.accountNumber').text();
						removeAccount(accountID, accountNumber);
						return false;
					});
					
					// add line effects
					$('#listAccountTable tr').hover(
						function(){
							$(this).addClass('highlight');
						}, 
						function(){
							$(this).removeClass('highlight');
						}
					);
					
					// init quick tips for edit and remove links
					quickTip();
				} // end success function				
		); // end $.get function	
	}
	
	//////////////////////////////////////// Quick tips //////////////////////////////////////
	function quickTip()
	{
		$(".editAccount").qtip({
			content: "Sửa trạng thái",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
		$(".removeAccount").qtip({
			content: "Xóa tài khoản",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
	} // end quickTip function


	
	///////////////////// Event helpers ///////////////////////////
	function editAccount(accountID)
	{
		accountID = parseInt(accountID);
		
		if (accountID > 0)
		{
			$.get("/account/get-account-status", {id: accountID}, function(data){
				
				var returnData = $.parseJSON(data);				
				if (returnData.code == 0)
				{
					$("#editAccountErrorRow").css("display", "none");		
					
					if (returnData.data.STATUS == 0)
						$("#editAccountStatusPending").attr("checked", true);
					else
						$("#editAccountStatusFinished").attr("checked", true);
										
					$("#editAccountStatusID").val(accountID);
					$("#editAccountDialog").dialog("open");
				}
			});
		}
	}
	function removeAccount(accountID, accountNumber)
	{
		accountID = parseInt(accountID);
		if (accountID > 0)
		{
			$("#removeShowAccountID").html(accountNumber);
			$("#removeAccountID").val(accountID);
			$("#removeAccountDialog").dialog("open");
		}
	}	
	
	//////////////////////// init functions //////////////////
	function initEditAccountDialog()
	{
		$("#editAccountDialog").dialog({
			autoOpen: false,
			width: 300,
			resizable: false,
			buttons: {
				"Cập nhật": function(){
					$("#editAccountErrorRow").css("display", "none");
					$.post("/account/edit-account-status", $("#editAccountForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							loadAccount();
							$('#editAccountDialog').dialog("close");												
						}
						else
						{
							$("#editAccountErrorRow").css("display", "");
							$("#editAccountErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$("#editAccountFilename").val("");				
			}
		});
	}
	
	function initRemoveAccountDialog()
	{
		$("#removeAccountDialog").dialog({
			autoOpen: false,
			width: 250,
			resizable: false,
			buttons: {
				"Xóa": function(){
					$.post("/account/remove", $("#removeAccountForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							loadAccount();
							$('#removeAccountDialog').dialog("close");
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			}
		});
	}
});